<!-- 搜索页面组件 -->
<template>
  <div class="m-hmsrch">
    <van-search v-model="value" autofocus background="#fbfcfd" clear-trigger="focus" @search="record" @input="fit" @focus="fit" shape="round" placeholder="搜索歌曲、歌手、专辑" />
    <div v-show="!issueless">
      <div v-show="!value" class="m-default">
        <!-- 热门搜索 -->
        <section class="m-hotlist">
          <h3 class="title">热门搜索</h3>
          <ul class="list">
            <li class="item f-bd f-bd-full" v-for="(item, index) in hotArr" :key="index">
              <span class="link" @click="record(item.first)">{{ item.first }}</span>
            </li>
          </ul>
        </section>
        <!-- 搜索记录 -->
        <section class="m-history">
          <van-cell :title="i" icon="clock-o" v-for="(i, index) in searecHistory" :key="index" @click="delline($event, i)" clickable>
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #right-icon>
              <van-icon name="cross" class="search-icon" />
            </template>
          </van-cell>
        </section>
      </div>
      <!-- 查询显示相关歌曲 -->
      <section v-show="value && !isFit" class="m-recom">
        <h3 class="title f-bd f-bd-btm f-thide" @click="record(value)">搜索“{{ value }}”</h3>
        <!-- 搜索中显示 -->
        <van-empty image="network" description="搜索中" v-show="descrip" />
        <!-- 搜索内容相关显示 -->
        <ul v-show="!descrip">
          <li class="recomitem" v-for="(items, index) in suggeation" :key="index" @click="record(items.keyword)">
            <i class="u-svg u-svg-search"></i>
            <span class="f-bd f-bd-btm f-thide">{{ items.keyword }}</span>
          </li>
        </ul>
      </section>
      <!-- 最佳匹配显示 -->
      <div v-show="value && isFit" class="m-searchresult">
        <section class="m-matchlist">
          <h3 class="title">最佳匹配</h3>
          <ul>
            <!-- 歌手 -->
            <li class="matchitem album" v-if="multimatch.artist" @click="$router.push(`/singerdetails?id=${multimatch.artist[0].id}`)">
              <album-view :album="multimatch.artist" :type="0" :values="value"></album-view>
            </li>
            <!-- 专辑 -->
            <li class="matchitem artist" v-if="multimatch.album" @click="$router.push(`/albumart?id=${multimatch.album[0].id}`)">
              <album-view :album="multimatch.album" :type="1" :values="value"></album-view>
            </li>
            <!-- 歌单 -->
            <li class="matchitem artist" v-if="multimatch.playlist" @click="$router.push(`/songlist?id=${multimatch.playlist[0].id}`)">
              <album-view :album="multimatch.playlist" :type="2" :values="value"></album-view>
            </li>
          </ul>
        </section>
        <section>
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadMore">
            <search-songs-list :songslist="songsList" :values="value"></search-songs-list>
          </van-list>
        </section>
      </div>
    </div>
    <!-- 搜索结果为空 -->
    <div v-show="issueless" class="m-searchresult">
      <div class="m-noresult">暂无搜索结果</div>
    </div>
  </div>
</template>

<script>
import { hotSearchAPI, multimatchAPI, searchResultListAPI, suggeationsAPI } from '@/api'
import AlbumView from './AlbumView.vue'
import SearchSongsList from './SearchSongsList.vue'
export default {
  components: { AlbumView, SearchSongsList },
  data() {
    return {
      value: '', // 搜索内容
      hotArr: [], // 热搜推荐
      searecHistory: [], // 搜索记录
      isFit: false, //最佳匹配显示与隐藏
      songsList: [], //搜索结果的歌曲列表
      suggeation: [], //搜索建议
      multimatch: [], //多重匹配
      descrip: false, //加载中状态显示
      issueless: false, //没有结果显示

      loading: false, // 搜索结果加载状态
      finished: false, // 搜索结果触底状态
      offset: 0, // 数据偏移量
    }
  },
  created() {
    //获取推荐关键字
    hotSearchAPI().then((res) => {
      this.hotArr = res.data.result.hots
    })
  },
  mounted() {
    this.searec()
  },
  methods: {
    //本地储存地址
    searec() {
      if (!localStorage.getItem('searecList')) {
        localStorage.getItem('searecList', '[]')
      } else {
        this.searecHistory = JSON.parse(localStorage.getItem('searecList'))
      }
    },
    suggeations() {
      suggeationsAPI(this.value).then((res) => {
        this.suggeation = res.data.result.allMatch
      })
    },
    //回车记录搜索内容
    record(val) {
      //去除文字的空格
      val = val.replace(/\s/g, '')
      // 空字符串不执行搜索方法
      if (!val) {
        this.issueless = true
        return
      } else {
        this.issueless = false
      }
      //显示最佳匹配
      this.isFit = true
      //搜索结果
      this.offset = 0
      searchResultListAPI({ keywords: val, offset: 0 }).then((res) => {
        this.songsList = res.data.result.songs
      })
      //搜索多重匹配
      multimatchAPI({ keywords: val }).then((res) => {
        this.multimatch = res.data.result
      })
      //记录搜索内容
      this.value = val
      this.searecHistory.unshift(val || this.value)
      let historyArr = new Set(this.searecHistory)
      localStorage.setItem('searecList', JSON.stringify(Array.from(historyArr)))
      this.searec()
    },
    // 点击删除记录事件
    delline(e, i) {
      if (e.target.className == 'search-icon van-icon van-icon-cross') {
        let fil = this.searecHistory.filter(function (item) {
          return item != e.path[1].innerText
        })
        this.searecHistory = fil
        localStorage.setItem('searecList', JSON.stringify(fil))
        this.searecHistory = JSON.parse(localStorage.getItem('searecList'))
      } else {
        // 点击记录实现搜索/置顶
        this.value = i
        this.isFit = true
        this.record(i)
      }
    },
    //输入框变化
    fit() {
      this.isFit = false
      this.issueless = false
      if (!this.value.replace(/\s/g, '')) {
        this.descrip = true
      } else {
        this.descrip = false
        this.suggeations()
      }
    },
    // 触底加载
    loadMore() {
      this.offset += 30
      this.loading = true
      let data = {
        keywords: this.value,
        offset: this.offset,
      }
      // 发送http请求,获取当前类别下的下一页数据,更新列表
      searchResultListAPI(data).then((res) => {
        if (this.offset >= res.data.result.songCount) {
          // 数据全部加载完成
          this.finished = true
        } else {
          this.songsList = [...this.songsList, ...res.data.result.songs]
          // 加载状态结束
          this.loading = false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.m-hmsrch {
  background: #fbfcfd;
  border-top: 1px solid #ccc;
  ::v-deep .van-search {
    .van-search__content {
      background-color: #ebecec;
    }
  }
  .m-default {
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    .m-hotlist {
      padding: 15px 10px 0;
      .title {
        font-size: 12px;
        line-height: 12px;
        color: #666;
        font-weight: 400;
        margin: 0;
      }
      .list {
        margin: 10px 0 7px;
        position: relative;
        & > li {
          list-style: none;
        }
        .link {
          color: #333;
        }
        .f-bd:after {
          width: 200%;
          height: 200%;
          transform: scale(0.5);
          position: absolute;
          z-index: 2;
          content: '';
          top: 0;
          left: 0;
          pointer-events: none;
          box-sizing: border-box;
          transform-origin: top left;
          border: 0 solid rgba(0, 0, 0, 0.1);
        }
        .item {
          display: inline-block;
          height: 32px;
          margin: 0 8px 8px 0;
          padding: 0 14px;
          font-size: 14px;
          line-height: 32px;
          border: 1px solid #d3d4da;
          border-radius: 32px;
        }
      }
    }
  }
  .m-recom {
    margin: 0 auto;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    h3 {
      margin: 0;
    }
    .title {
      height: 50px;
      margin-left: 10px;
      padding-right: 10px;
      font-size: 15px;
      line-height: 50px;
      color: #507daf;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }
    .recomitem {
      display: flex;
      align-items: center;
      height: 45px;
      padding-left: 10px;
    }
    i {
      flex: 0 0 auto;
      margin-right: 7px;
    }
    span {
      display: inline-block;
      flex: 1;
      width: 1%;
      padding-right: 10px;
      font-size: 15px;
      line-height: 45px;
      color: #333;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }
    span:after {
      border-color: rgba(0, 0, 0, 0.1);
    }
  }
}
.m-searchresult {
  background: #fcfcfd;
}
.m-noresult {
  padding: 20px 0;
  text-align: center;
}
.f-bd {
  position: relative;
}
.f-thide {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: normal;
}
.u-svg-search {
  width: 15px;
  height: 15px;
  background-image: url('../assets/img/search.svg');
}
.u-svg {
  display: inline-block;
  vertical-align: middle;
  background-position: 0 0;
  background-size: contain;
  background-repeat: no-repeat;
}
.m-searchresult {
  background: #fcfcfd;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  .m-matchlist {
    padding: 8px 0 4px;
    h3 {
      margin: 0;
    }
    .title {
      margin-left: 10px;
      font-size: 12px;
      line-height: 16px;
      color: #666;
    }
    .matchitem {
      position: relative;
      height: 66px;
    }
  }
}
</style>
